package cn.bearspark.collect.provider.rpc.impl;

import cn.bearspark.collect.provider.dao.buffer.CollectUserIdZSetBuffer;
import cn.bearspark.collect.provider.dao.mapper.CollectMapper;
import cn.bearspark.collect.provider.service.CollectService;
import cn.bearspark.common.enumeration.CollectedEnum;
import org.springframework.stereotype.Service;

/**
 * @author f
 */
@Service
public class CollectServiceImpl implements CollectService {

    private final CollectMapper collectMapper;

    private final CollectUserIdZSetBuffer collectUserIdZSetBuffer;

    public CollectServiceImpl(CollectMapper collectMapper,
                              CollectUserIdZSetBuffer collectUserIdZSetBuffer) {
        this.collectMapper = collectMapper;
        this.collectUserIdZSetBuffer = collectUserIdZSetBuffer;
    }

    @Override
    public boolean collect(long userId, int moduleCode, long moduleDataId, int collected) {
        boolean isCollected = isCollected(userId, moduleCode, moduleDataId);

        if (collected == CollectedEnum.COLLECTED.getCode()) {
            // 如果用户 收藏过 该数据，则不能再次 收藏
            if (isCollected) {
                return false;
            }
            // 否则保存记录
            return collectMapper.insert(userId, moduleCode, moduleDataId) > 0;
        } else {
            // 如果用户没有 收藏过 该评论，则不能取消 收藏
            if (!isCollected) {
                return false;
            }
            // 否则删除记录
            int row = collectMapper.delete(userId, moduleCode, moduleDataId);
            // 清理用户的 收藏数据 缓存
            collectUserIdZSetBuffer.clean(userId, moduleCode, moduleDataId);
            return row > 0;
        }
    }

    @Override
    public boolean isCollected(long userId, int moduleCode, long moduleDataId) {
        return collectUserIdZSetBuffer.exists(userId, moduleCode, moduleDataId);
    }
}
